package com.gamota.mobi;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.androidquery.AQuery;

import com.devsmart.android.ui.HorizontalListView;
import com.gamota.mobi.adapter.ErrorHandler;
import com.gamota.mobi.background.BackgroundTasks;
import com.gamota.mobi.db.DatabaseHelper;
import com.gamota.mobi.event.Event;
import com.gamota.mobi.model.RecommendItem;
import com.gamota.mobi.util.Constants;
import com.gamota.mobi.util.Utils;
import com.gamota.mobi.view.FlowLayout;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.util.AsyncExecutor;
import de.greenrobot.event.util.AsyncExecutor.RunnableEx;

public class SearchActivity extends SherlockActivity implements TextWatcher, OnClickListener, OnItemClickListener {
	
	private String searchType;
	private String currentStore;
	private DatabaseHelper db;
	private HorizontalListView recommendListView;
	private FlowLayout tagsContainer;
	private AQuery aq;
	private BackgroundTasks bgTask;
	private List<Integer> colorList;
	private AutoCompleteTextView searchText;
	private String store;
	private String accessToken;
	private RecommendItemAdapter adapter;
	private List<RecommendItem> recommList;
	private Typeface robotoItalic;
	private Typeface robotoCond;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		searchType = getIntent().getStringExtra(Constants.SEARCH_TYPE);
		if(searchType == null){
			searchType = "all";
		}
//		if(searchType.equalsIgnoreCase("apps")){
			currentStore = "apps";
			setTheme(R.style.Theme_Styled_Home);
			setThemeLowEndDevice(R.drawable.action_bar_home);
			store = Constants.ANDROID_STORE;
//		} else if(searchType.equalsIgnoreCase("books")){
//			currentStore = "books";
//			setTheme(R.style.Theme_Styled_Book);
//			setThemeLowEndDevice(R.drawable.action_bar_book);
//			store = "ebook";
//		} else if(searchType.equalsIgnoreCase("comics")){
//			currentStore = "comics";
//			setTheme(R.style.Theme_Styled_Comic);
//			setThemeLowEndDevice(R.drawable.action_bar_comic);
//			store = "comic";
//		} else if(searchType.equalsIgnoreCase("movies")){
//			currentStore = "movies";
//			setTheme(R.style.Theme_Styled_Movie);
//			setThemeLowEndDevice(R.drawable.action_bar_movie);
//			store = "film";
//		} else {
//			currentStore = "apps";
//			store = Constants.ANDROID_STORE;
//			setTheme(R.style.Theme_Styled_Apps);
//			setThemeLowEndDevice(R.drawable.action_bar_apps);
//		}
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		EasyTracker.getInstance().setContext(this);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setTitle(R.string.search);
		robotoCond = Typeface.createFromAsset(getAssets(), getResources().getString(R.string.roboto_bold_condensed));
		robotoItalic = Typeface.createFromAsset(getAssets(), getResources().getString(R.string.roboto_italic_condensed));
		
		db = new DatabaseHelper(this);
		bgTask = new BackgroundTasks(this);
		aq = new AQuery(this);
		aq.id(R.id.btn_clear_search).clicked(this);
		aq.id(R.id.btn_search).clicked(this);
		aq.id(R.id.text_hot_tags).typeface(robotoItalic);
		aq.id(R.id.text_recommend).typeface(robotoItalic);
		recommendListView = (HorizontalListView) findViewById(R.id.recommend_list);
		tagsContainer = (FlowLayout) findViewById(R.id.tags_container);
		searchText = (AutoCompleteTextView) findViewById(R.id.text_search);
		searchText.addTextChangedListener(this);
		searchText.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int pos, long arg3) {
				// TODO Auto-generated method stub
				startSearch((String) parent.getItemAtPosition(pos));
			}
		});
		searchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
		    @Override
		    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
		        	if(!TextUtils.isEmpty(searchText.getText().toString())){
		        		db.addSearchQuery(searchText.getText().toString());
			        	startSearch(searchText.getText().toString());
			            return true;
		        	} else {
		        		Toast.makeText(SearchActivity.this, R.string.input_search, Toast.LENGTH_SHORT).show();
		        		return true;
		        	}
		        }
		        return false;
		    }
		});
		
		int[] colors = getResources().getIntArray(R.array.tag_colors);
		colorList = new ArrayList<Integer>();
		for(int i=0; i < colors.length; i++){
			colorList.add(colors[i]);
		}
		recommList = new ArrayList<RecommendItem>();
		adapter = new RecommendItemAdapter(this, R.layout.recommend_item, recommList);
		aq.id(recommendListView).adapter(adapter).itemClicked(this);
		
		getRecentSearch();
		getHotKeywords();
		getRecommendItems();
	}
	
	private void setThemeLowEndDevice(int drawableId){
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(drawableId);
            bg.setTileModeX(TileMode.REPEAT);
            getSupportActionBar().setBackgroundDrawable(bg);
        }
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		EasyTracker.getInstance().activityStop(this);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EasyTracker.getInstance().activityStart(this);
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		EventBus.getDefault().unregister(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		UILApplication myApp=UILApplication.getInstance();
		Configuration config = myApp.getConfig();  
		getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
		super.onResume();
		EventBus.getDefault().register(this);
	}
	
	private void getRecentSearch(){
		AsyncExecutor.create().execute(new RunnableEx() {
			@Override
			public void run() throws Exception {
				List<String> keywordList = db.getAllRecentSearch();
				EventBus.getDefault().post(new Event.RecentSearchLoadedEvent(keywordList));
			}
		});
	}
	
	private void startSearch(String query){
		EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.SEARCH_EVENT_ACTION, "search keyword: " + query, Long.valueOf(1));
		Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
		intent.putExtra(Constants.SEARCH_QUERY, query);
		intent.putExtra(Constants.STORE_KEY, searchType);
		startActivity(intent);
		searchText.setText("");
	}
	
	public void onEventMainThread(Event.RecentSearchLoadedEvent event){
		searchText.setAdapter(new SuggestionAdapter(this, R.layout.suggestion_item, event.getKeywordList()));
	}
	
	private void getHotKeywords(){
		accessToken = Utils.getStaticAccessToken(this);
		bgTask.getHotKeywords(accessToken, store, "20");
	}
	
	public void onEventMainThread(Event.HotKeywordSuccessEvent event){
		aq.id(R.id.progress_tags).gone();
		aq.id(R.id.btn_retry_tags).gone();
		aq.id(tagsContainer).visible();
		TextView tag = null;
		for(final String keyword : event.getKeywords()){
			tag = new TextView(this);
			tag.setText(keyword);
			tag.setPadding(5, 0, 5, 0);
			tag.setTextColor(getTagColor());
			tag.setSingleLine(true);
			if(!Utils.isTablet(getApplicationContext())){
				int textSize = 12 + (int)(Math.random() * ((40 - 12) + 1));
				tag.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
			} else {
				int textSize = 32 + (int)(Math.random() * ((80 - 32) + 1));
				tag.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
			}
			tag.setClickable(true);
			tag.setBackgroundDrawable(getResources().getDrawable(R.drawable.comic_list_selector));
			tag.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					startSearch(keyword);
				}
			});
			tagsContainer.addView(tag, new FlowLayout.LayoutParams(2, 0));
		}
	}
	
	public void onEventMainThread(Event.RequestFailEvent e){
		aq.id(R.id.progress_tags).gone();
		aq.id(R.id.btn_retry_tags).visible().clicked(this);
		aq.id(tagsContainer).gone();
		ErrorHandler.getInstance().setContext(this).handleError(e.getErrorCode());
	}
	
	private void getRecommendItems(){
		accessToken = Utils.getStaticAccessToken(this);
		int storeId = 2;
		if(store.equals("android")){
			storeId = 2;
		} else if(store.equals("ebook")){
			storeId = 4;
		} else if(store.equals("comic")){
			storeId = 5;
		} else if(store.equalsIgnoreCase("film")){
			storeId = 6;
		} else {
			storeId = 2;
		}
		bgTask.getRecommendItems(accessToken, String.valueOf(storeId), "0", "20");
	}
	
	public void onEventMainThread(Event.GetRecommentItemSuccessEvent event){
		aq.id(R.id.progress_recommend).gone();
		aq.id(R.id.btn_retry_recommend).gone();
		aq.id(recommendListView).visible();
		for(RecommendItem item : event.getRecommendList()){
			recommList.add(item);
		}
		adapter.notifyDataSetChanged();
	}
	
	public void onEventMainThread(Event.GetRecommendFailEvent e){
		if(e.getErrorCode()!=2){
			aq.id(R.id.progress_recommend).gone();
			aq.id(R.id.btn_retry_recommend).visible().clicked(this);
			aq.id(recommendListView).gone();
			ErrorHandler.getInstance().setContext(this).handleError(e.getErrorCode());
		}
	}
	
	public int getTagColor(){
		Random random = new Random();
		int index = random.nextInt(colorList.size());
		return colorList.get(index);
	}

	@Override
	public void afterTextChanged(Editable editable) {
		// TODO Auto-generated method stub
		if(TextUtils.isEmpty(editable.toString())){
			aq.id(R.id.btn_clear_search).invisible();
		} else {
			aq.id(R.id.btn_clear_search).visible();
		}
	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private class SuggestionAdapter extends ArrayAdapter<String>{
		
		private LayoutInflater inflater;

		public SuggestionAdapter(Context context, int textViewResourceId, List<String> objects) {
			super(context, textViewResourceId, objects);
			// TODO Auto-generated constructor stub
			inflater = getLayoutInflater();
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			SuggestionHolder holder = null;
			if(convertView == null){
				holder = new SuggestionHolder();
				convertView = inflater.inflate(R.layout.suggestion_item, null);
				holder.text = (TextView) convertView.findViewById(R.id.txt_suggestion);
				convertView.setTag(holder);
			} else {
				holder = (SuggestionHolder) convertView.getTag();
			}
			String suggest = getItem(position);
			if(suggest != null){
				holder.text.setText(suggest);
			}
			return convertView;
		}
	}
	
	private static class SuggestionHolder {
		TextView text;
	}
	
	private class RecommendItemAdapter extends ArrayAdapter<RecommendItem> {
		
		private AQuery aq;
		private LayoutInflater inflater;

		public RecommendItemAdapter(Context context, int textViewResourceId, List<RecommendItem> objects) {
			super(context, textViewResourceId, objects);
			// TODO Auto-generated constructor stub
			inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			RecommendViewHolder holder = null;
			if(convertView == null){
				holder = new RecommendViewHolder();
				convertView = inflater.inflate(R.layout.recommend_item, null);
				holder.image = (ImageView) convertView.findViewById(R.id.recommend_icon);
				holder.name = (TextView) convertView.findViewById(R.id.recommend_name);
				holder.price = (TextView) convertView.findViewById(R.id.recommend_price);
				holder.rating = (RatingBar) convertView.findViewById(R.id.recommend_rating);
				convertView.setTag(holder);
			} else {
				holder = (RecommendViewHolder) convertView.getTag();
			}
			RecommendItem item = getItem(position);
			if(item != null){
				aq = new AQuery(convertView);
				aq.id(holder.image).image(item.getImageUrl(), false, true);
				aq.id(holder.name).text(item.getName()).typeface(robotoCond);
				if(item.getPrice() == 0 && item.getPrice2() != 0){
					aq.id(holder.price).text(String.valueOf(item.getPrice2()));
				} else if(item.getPrice() != 0 && item.getPrice2() == 0){
					aq.id(holder.price).text(String.valueOf(item.getPrice()));
				} else {
					aq.id(holder.price).text(R.string.free);
				}
				if(item.getTotalRate() > 0){
					aq.id(holder.rating).rating(item.getSumRate() / item.getTotalRate());
				} else {
					aq.id(holder.rating).rating(0);
				}
			}
			return convertView;
		}
	}
	
	private static class RecommendViewHolder{
		ImageView image;
		TextView name;
		TextView price;
		RatingBar rating;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_clear_search:
			searchText.setText("");
			break;
		case R.id.btn_search:
			if(!TextUtils.isEmpty(searchText.getText().toString())){
				db.addSearchQuery(searchText.getText().toString());
				startSearch(searchText.getText().toString());
			} else {
				Toast.makeText(SearchActivity.this, R.string.input_search, Toast.LENGTH_SHORT).show();
			}
 			break;
		case R.id.btn_retry_tags:
			aq.id(R.id.btn_retry_tags).gone();
			aq.id(R.id.progress_tags).visible();
			getHotKeywords();
			break;
		case R.id.btn_retry_recommend:
			aq.id(R.id.btn_retry_recommend).gone();
			aq.id(R.id.progress_recommend).visible();
			getRecommendItems();
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int pos, long arg3) {
		// TODO Auto-generated method stub
		RecommendItem item = (RecommendItem) parent.getItemAtPosition(pos);
		EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.VIEW_EVENT_ACTION, item.getName(), Long.valueOf(1));
		Intent intent = new Intent(this, ItemBrokerActivity.class);
		intent.putExtra(Constants.PREVIOUS_SCREEN, store + "/recommend");
		intent.putExtra(Constants.SLUG, item.getSlug());
		intent.putExtra(Constants.KEY_REFERER, "direct");
		intent.putExtra(Constants.STORE_KEY, currentStore);
		startActivity(intent);
	}

}
